//
//  RwdUserAcount.swift
//  Weibo_rwd
//
//  Created by 任文迪 on 16/7/12.
//  Copyright © 2016年 spaceX. All rights reserved.
//

import UIKit

class RwdUserAcount: NSObject,NSCoding{
    
    //  用户授权的唯一标识
    var access_token: String?
    //  access_token的生命周期
    var expires_in: NSTimeInterval = 0 {
        didSet {
            //  access_token过期时间
            expiresDate = NSDate().dateByAddingTimeInterval(expires_in)
        }
    }
    //  过期时间
    var expiresDate: NSDate?
    //  授权用户的UID
    var uid: Int64 = 0
    //  用户名
    var name: String?
    //  用户头像
    var avatar_large: String?
    
    init(dict:[String: AnyObject]){
        super.init()
        
        setValuesForKeysWithDictionary(dict)
        
    }
    //setValueFor undefinedKey重写
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
    //  归档
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(expiresDate, forKey: "expiresDate")
        aCoder.encodeInt64(uid, forKey: "uid")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
        
    }
    //  解档
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expiresDate = aDecoder.decodeObjectForKey("expiresDate") as? NSDate
        uid = aDecoder.decodeInt64ForKey("uid")
        name = aDecoder.decodeObjectForKey("name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
    }
    //存
    func saveToUserData() -> Bool {
        
        let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("user.count")
        
        let rusult = NSKeyedArchiver.archiveRootObject(self, toFile: path)
        
        print(rusult)
        
        return rusult
        
    }
    //取
      class func unArchiverUserData() -> RwdUserAcount?{
        
        let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("user.count")
        let result = NSKeyedUnarchiver.unarchiveObjectWithFile(path)
        
        print(result)
        
        return result as?RwdUserAcount
        
    }
    
    
    
    

}
